//
//  WPReadingViewCollectionViewChargeCellVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/28.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPReadingViewCollectionViewChargeCellVC.h"
#import "WPNewReadingIndivalCaseCell.h"
#import "WPMRModel.h"
#import "UITableView+FDTemplateLayoutCell.h"

@interface WPReadingViewCollectionViewChargeCellVC ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,WPNewReadingIndivalCaseCellDelegate>

@property(nonatomic,strong)UIView *noNetWorkView;
@property(nonatomic,strong)UIView *noDataView;
@property(nonatomic,strong)NSMutableArray *chargeArr;

@property(nonatomic,assign)int indexPage;

@end

@implementation WPReadingViewCollectionViewChargeCellVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = GlobalBgColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedRowHeight = 200;
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    [self.tableView registerClass:[WPNewReadingIndivalCaseCell class] forCellReuseIdentifier:@"WPNewReadingIndivalCaseCell"];
    
    /* 配置下拉刷新控件 */
    MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //      刷新数据
        [self refreshData];
        
    }];
    self.tableView.mj_header = mj_header;
    [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    mj_header.stateLabel.textColor = GLobalFontColor;
    mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
    
    //    上拉刷新控件
    MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];
        
    }];
    self.tableView.mj_footer = mj_footer;
    mj_footer.automaticallyRefresh = NO;
    mj_footer.automaticallyHidden = NO;
    
    //判断网络状态
    ReachabilityStatus status = [[RealReachability sharedInstance] currentReachabilityStatus];
    if (status == RealStatusNotReachable)
    {
        [self noNetWorkView];
    }
    else
    {
        [self loadChargeData];
    }
}

-(void)loadChargeData
{
//    [self showWithStatus:@"正在加载"];
    
    NSString *url = @"record/searchRecord.do";
    NSDictionary *dict = nil;
    
    if (self.isFiveDiseases)
    {
        dict = @{@"diseaseCategoryId":self.diseaseCategoryId,@"page":@(0),@"payable":@(1)};
    }
    else if (self.isPartOfHuman)
    {
        url = @"record/findByName.do";
         dict = @{@"name":self.diseaseCategoryId,@"page":@(0),@"payable":@(1)};
    }
    else
    {
        dict = @{@"page":@(0),@"payable":@(1)};
    }
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            [self.chargeArr removeAllObjects];
            
            for (NSDictionary *dict in responseDict[@"detail"])
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                [self.chargeArr addObject:model];
            }
            
            //不满一页就隐藏
            if (self.chargeArr.count == 0)
            {
//                [self dismiss];
                [self noDataView];
                return  ;
            }
            else if (self.chargeArr.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
//            [self dismiss];
            
            self.noDataView.hidden = YES;
            [self.tableView reloadData];
            
            self.indexPage = 1;
        }
        else
        {
//            [self dismiss];
            
            //考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      [self dismiss];
      [self showErrorInfoWithStatus:@"网络错误"];
    }];
    
}

-(void)refreshData
{
    NSString *url = @"record/searchRecord.do";;
    NSDictionary *dict = nil;
    
    if (self.isFiveDiseases)
    {
        dict = @{@"diseaseCategoryId":self.diseaseCategoryId,@"page":@(0),@"payable":@(1)};
    }
    else if (self.isPartOfHuman)
    {
        url = @"record/findByName.do";
        dict = @{@"name":self.diseaseCategoryId,@"page":@(0),@"payable":@(1)};
    }
    else
    {
        dict = @{@"page":@(0),@"payable":@(1)};
    }
    
    self.indexPage = 1;
    
    [self.tableView.mj_footer endRefreshing];
    
    [[WPViewModel sharedInstance] loadDataWithURL:url parameters:dict finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            
            [self.chargeArr removeAllObjects];
            
            for (NSDictionary *dict in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                [self.chargeArr addObject:model];
            }
            
            if (dictsArr.count == 0)
            {
                self.noDataView.hidden = NO;
                [self.tableView.mj_header endRefreshing];
                return ;
            }
            else if (dictsArr.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
            self.noDataView.hidden = YES;
            [self.tableView reloadData];
        }
        
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)loadMoreData
{
    NSString *url = @"record/searchRecord.do";
    NSDictionary *dict = nil;
    
    if (self.isFiveDiseases)
    {
        dict = @{@"diseaseCategoryId":self.diseaseCategoryId,@"page":@(self.indexPage),@"payable":@(1)};
    }
    else if (self.isPartOfHuman)
    {
        url = @"record/findByName.do";
        dict = @{@"name":self.diseaseCategoryId,@"page":@(self.indexPage),@"payable":@(1)};
    }
    else
    {
        dict = @{@"page":@(self.indexPage),@"payable":@(1)};
    }
    
    [[WPViewModel sharedInstance] loadDataWithURL:url parameters:dict finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            for (NSDictionary  *obj in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                [self.chargeArr addObject:model];
            }
            
            self.indexPage++;
            
            //            不满一页就隐藏
            if (dictsArr.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
            //            刷新数据
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    }];
}

#pragma mark - alertView的代理方法
//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        WPMineLoginVC *vc = [WPMineLoginVC new];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
    }
}

#pragma mark - tableView的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chargeArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewReadingIndivalCaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPNewReadingIndivalCaseCell"];
     WPMRModel *model = self.chargeArr[indexPath.item];
    cell.model = model;
    cell.delegate = self;
    
    cell.tapTriggered = ^{
        
        [self pushDiseaseDetailVC:model];
    };
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"WPNewReadingIndivalCaseCell" cacheByIndexPath:indexPath configuration:^(WPNewReadingIndivalCaseCell *cell) {
        // 配置 cell 的数据源，和 "cellForRow" 干的事一致，比如：
        cell.model = self.chargeArr[indexPath.item];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPMRModel *model = self.chargeArr[indexPath.item];
    [self pushDiseaseDetailVC:model];
}

#pragma mark - WPNewReadingIndivalCaseCellDelegate的代理方法
-(void)WPNewReadingIndivalCaseCellDiseaseDidClick:(WPNewReadingIndivalCaseCell *)cell disease:(NSString *)disease
{
    if ([self.delegate respondsToSelector:@selector(chargeCaseCellDidClickDiseaseWith:disease:)])
    {
        [self.delegate chargeCaseCellDidClickDiseaseWith:self disease:disease];
    }
}

-(UIView *)noDataView
{
    if (_noDataView == nil)
    {
        _noDataView = [[UIView alloc] initWithFrame:self.view.bounds];
        _noDataView.backgroundColor = GlobalBgColor;
        
        [self.view addSubview:_noDataView];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"collection_record"]];
        [_noDataView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noDataView);
            make.top.equalTo(_noDataView).offset(138*K_SCALE_ELSE_TABBAR);
        }];
        
        UILabel *label = [UILabel new];
        label.text = @"暂无数据";
        label.textColor = GloballightFontColor;
        label.font = [UIFont systemFontOfSize:15];
        [_noDataView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noDataView);
            make.top.equalTo(imageView.mas_bottom).offset(30*K_SCALE_ELSE_TABBAR);
        }];
    }
    return _noDataView;
}

-(UIView *)noNetWorkView
{
    if (_noNetWorkView == nil)
    {
        _noNetWorkView = [[UIView alloc] initWithFrame:self.view.bounds];
        _noNetWorkView.backgroundColor = GlobalBgColor;
        [self.view addSubview:_noNetWorkView];
        
        
        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noNetWork"]];
        [iconView sizeToFit];
        [_noNetWorkView addSubview:iconView];
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(_noNetWorkView).offset(65);
        }];
        
        UILabel *tipLabel = [UILabel new];
        tipLabel.textColor = GloballightFontColor;
        tipLabel.font = [UIFont systemFontOfSize:14];
        tipLabel.text = @"网络请求失败,请检查您的网络设置";
        [_noNetWorkView addSubview:tipLabel];
        
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(iconView.mas_bottom).offset(30);
        }];
        
        UIButton *loadAgainBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [loadAgainBtn setTitle:@"重新加载" forState:UIControlStateNormal];
        loadAgainBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [loadAgainBtn setTitleColor:GloballightFontColor forState:UIControlStateNormal];
        [loadAgainBtn setTitleColor:GlobalColor forState:UIControlStateHighlighted];
        [loadAgainBtn setBackgroundImage:[UIImage imageNamed:@"loadAgain_normal"] forState:UIControlStateNormal];
        [loadAgainBtn setBackgroundImage:[UIImage imageNamed:@"loadAgain_highlight"] forState:UIControlStateHighlighted];
        
        [loadAgainBtn addTarget:self action:@selector(loadAgainBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [_noNetWorkView addSubview:loadAgainBtn];
        
        [loadAgainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(105);
            make.height.mas_equalTo(31);
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(tipLabel.mas_bottom).offset(16);
        }];
        
    }
    return _noNetWorkView;
}

#pragma mark - 跳转病例详情页的代理方法
-(void)pushDiseaseDetailVC:(WPMRModel *)model
{
    if ([self.delegate respondsToSelector:@selector(chargeCaseCellDidClickWith:model:)])
    {
        [self.delegate chargeCaseCellDidClickWith:self model:model];
    }
}

-(void)loadAgainBtnDidClick:(UIButton *)btn
{
//    ReachabilityStatus status = [[RealReachability sharedInstance] currentReachabilityStatus];
//    if (status != RealStatusNotReachable)
//    {
        self.noNetWorkView.hidden = YES;
        [self loadChargeData];
//    }
}

-(NSMutableArray *)chargeArr
{
    if (_chargeArr == nil)
    {
        _chargeArr = [NSMutableArray array];
    }
    return _chargeArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
